package com.plat.service.impl;

import java.util.Collection;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import com.plat.dao.IBaseDao;
import com.plat.security.dao.SysUsersDao;
import com.plat.security.entity.SysUsers;
import com.plat.security.entity.SysUsersRoles;
import com.plat.service.ISysRoles;
import com.plat.service.ISysUsersRoles;
import com.plat.service.ISysUsersService;

@Service
public class SysUsersServiceImpl extends BaseServiceImpl<SysUsers> implements ISysUsersService {

    @Autowired
    private SysUsersDao sysUsersDao;

    @Autowired
    private ISysRoles roleService;

    @Autowired
    private ISysUsersRoles sysUserRoleService;

    @Override
    public IBaseDao<SysUsers> getDao() {
        return sysUsersDao;
    }

    @Override
    public Collection<GrantedAuthority> loadUserAuthoritiesByName(String username) {
        return sysUsersDao.loadUserAuthoritiesByName(username);
    }

    @Override
    public SysUsers findByUserAccount(String username) {
        return sysUsersDao.findByUserAccount(username);
    }

    @Override
    public void save(Object o) {
        super.save(o);
    }

    @Override
    public void updateMerge(Object o) {
        SysUsers user = (SysUsers) o;
        super.updateMerge(o);
        if (StringUtils.isNotEmpty(user.getRoleIds())) {
            String[] roles = user.getRoleIds().split(",");
            List<SysUsersRoles> sysRoles = sysUserRoleService.findBy("userId", user.getUserId());

            //删除旧的角色设置
            for (SysUsersRoles ur : sysRoles) {
                sysUserRoleService.remove(ur);
            }
            //重新添加新的角色
            SysUsersRoles sur = null;
            for (String str : roles) {
                sur = new SysUsersRoles();
                sur.setUserId(user.getUserId());
                sur.setRoleId(str);
                sur.setEnabled(true);
                sysUserRoleService.save(sur);
            }

        }
    }
}
